package com.situ.skymallimageapi.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtil {
    //获取配置信息
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    //上传图片的方法
    public String upload(MultipartFile multipartFile, String type) throws IOException {
        //获取上传文件输入流
        InputStream inputStream = multipartFile.getInputStream();
        //避免文件覆盖 更换文件名
        String originalFilename = multipartFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() +
                originalFilename.substring(originalFilename.lastIndexOf("."));

        // 构建OSS中的对象键（包含type路径）
        String objectName = type + "/" + newName;

        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //推送数据到OSS
        ossClient.putObject(bucketName, objectName, inputStream);
        //关闭OSSClient
        ossClient.shutdown();

        //还原文件名
        //https://sjt--java63--oss.oss-cn-beijing.aliyuncs.com/img/%E6%8E%A5%E5%8F%A3.txt
        StringBuffer stringBuffer = new StringBuffer(endpoint);//将endpoint放入stringBuffer 方便字符串插入 因为String是不可变的
        String url = stringBuffer.insert(8, bucketName + ".").append("/").append(objectName).toString();
        return url;
    }
}
